import { memo, useEffect } from 'react'
import { loadMapKey } from '@/utils/AmapLoader/LoadMapKey.ts'

const AMap = ({
  options,
  mapKey,
  plugins = [],
  optionsFunc,
  onMapClick
}: {
  options: any
  mapKey: string
  plugins: string[]
  optionsFunc: any
  onMapClick: (ev: any) => void
}) => {
  useEffect(() => {
    let finalMap
    loadMapKey(mapKey || 'e6f371d1dc1c35bf06d99e4ba6eaa6c8', plugins).then(() => {
      let afterCallback
      if (optionsFunc) {
        const mapData = optionsFunc(window.AMap, (callback) => {
          afterCallback = callback
        })
        finalMap = new window.AMap.Map('gaodeMap', mapData.options)
      } else {
        finalMap = new window.AMap.Map('gaodeMap', options)
      }

      // 执行回调函数
      afterCallback && afterCallback(finalMap)
      // 触发点击事件
      finalMap.on('click', (ev) => {
        onMapClick?.(ev)
      })
    })
  }, [])

  return <div id="gaodeMap" className="h-full" />
}

export default memo(AMap)
